package org.wheel.module.core.config.cookie.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;

import java.util.Arrays;
import java.util.Optional;

/**
 * 从请求中提取 token
 */
public class JwtTokenExtractor {

    // 直接使用 LogFactory 创建日志对象，Hutool 会自动检测项目中的日志框架（优先级：Slf4j > Log4j > Logback > JDK Logging）
    private static final Log log = LogFactory.get();

    private static final String COOKIE_NAME = HttpHeaders.AUTHORIZATION;   // 你的 cookie 名
    private static final String BEARER        = "Bearer";  // 你的 token 前缀, 默认是 “Bearer ”，有的服务器是 “Bearer+”

    /**
     * 优先级：cookie → header → query param
     * 返回纯 token（去掉 Bearer 前缀），找不到返回 null
     */
    public static String getToken(HttpServletRequest request) {
        /* 1. cookie */
        if (request.getCookies() != null) {
            Optional<String> fromCookie = Arrays.stream(request.getCookies())
                    .filter(c -> COOKIE_NAME.equals(c.getName()))
                    .map(Cookie::getValue)
                    .findFirst();
            if (fromCookie.isPresent()) {
                return removeBearer(fromCookie.get());
            }
        }

        /* 2. Authorization header */
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isNotBlank(header)) {
            return removeBearer(header);
        }

        /* 3. query param ?Authorization=xxx */
        String param = request.getParameter(COOKIE_NAME);
        if (StrUtil.isNotBlank(param)) {
            return removeBearer(param);
        }

        /* 3. query param ?token=xxx */
        param = request.getParameter("token");
        if (StrUtil.isNotBlank(param)) {
            return removeBearer(param);
        }

        return null;
    }

    private static String removeBearer(String value) {
        log.trace("从请求中提取 token: {}", value);
        if (value.startsWith(BEARER)) {
            return value.substring(BEARER.length()+1).trim();
        }
        return value.trim();
    }

    private JwtTokenExtractor() {}
}
